<?php
/*
Cogumelo v0.2 - Innoto S.L.
Copyright (C) 2010 Innoto Gestión para el Desarrollo Social S.L. <mapinfo@map-experience.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*/

class MysqlDAOutils
{
	//
	// Creates an "ORDER BY" String from $ORDER array
	//
	public static function OrderByString($ORDArray)
	{
		// Direction (ASC, DESC) Array
		if( is_array($ORDArray) )
		{
			$orderSTR = " ORDER BY ";
			$coma = "";
			foreach ($ORDArray as $elementK => $elementV)
			{
				if ($elementV < 0)
					$orderSTR .= $coma .$elementK." DESC";
				else
					$orderSTR .= $coma .$elementK." ASC";
				
				$coma=", ";
			}
			return $orderSTR;
		}
		else
			return "";
	}
	//
	// Execute a SQL query command
	//
	public static function execSQL($connection, $sql)
	{
		@ $result = $connection->Query($sql);
		return ($result);
	}
	
	
	//
	// Creates an VO from a query result;
	// Returns: Obj/false
	public static function VOGenerator($VO, &$res)
	{
		// IMPORTANTE: Avanza cursor en $res !!!
		$newObj = false;
		if( $row = mysqli_fetch_assoc($res) ) {
			$comando = '$newObj = new $VO($row);';

			eval($comando);
		}
	
		return $newObj;
	}
	
	//
	// Creates an VO array from a query result;
	// Returns: Obj's Array/false
	public static function VOArrayGenerator($VO, $res)
	{
		$list = false;
		
		while( $rowVO = self::VOGenerator($VO, $res) ) {
			$list[ $rowVO->getter($VO::$keyId) ] = $rowVO;
		}
		
		return $list;
	}
	
	
	//
	//	Generic Create
	//
	public static function Create($VO, $DAO, $connection, $VOobj, $customlogtext=false) 
	{
		// SQL Query
		$campos = '`'.implode('`,`', $VOobj::$keys).'`';

		$valArray = array();
		foreach( $VOobj::$keys as $colName ) {
			$val = eval('return $VOobj->getter("'.$colName.'");');
			$valArray[] = "'".$connection->real_escape_string( $val )."'";
		}
		$valores = implode(',', $valArray);
		
		$StrSQL = "INSERT INTO `".$VO::$tableName."` (".$campos.") VALUES(".$valores.");";
		if(!$customlogtext)	$customlogtext = $StrSQL;
		
		if($res = self::execSQL($connection,$StrSQL)) {
			Cogumelo::Log("SQL Query: mysql DAO:Create(): ".$customlogtext, 5);
			$VOobj->setter($VOobj::$keyId, $connection->insert_id);
			return $VOobj;
		}
		else {
			Cogumelo::Error(__METHOD__.$connection->error." QUERY: ".$customlogtext);
		}
	}
	
	//
	//  Generic Update
	// return: Vo updated from DB
	public static function Update($VO, $DAO, $connection, $VOobj, $customlogtext=false)
	{
		$listvalues=" ";
	
		foreach($VOobj::$keys as $k){
			if($VOobj->getter($k) != false){
				if($listvalues != " ")
					$listvalues .= " ,";

				$listvalues .= " ".$k." = '".$VOobj->getter($k)."' ";
			}
		}
	
		$StrSQL = "UPDATE `".$VO::$tableName."` SET
			    ".$listvalues." 
			  WHERE `". $VO::$keyId ."` = " . $VOobj->getter($VO::$keyId). " ;";											


		if($res = self::execSQL($connection,$StrSQL)) {
			Cogumelo::Log("SQL Query: mysql DAO:Create(): ".$customlogtext, 5);
			return self::Find($VO, $connection, $VOobj->getter($VO::$keyId));
				
		}
		else {
			Cogumelo::Error(__METHOD__.$connection->error." QUERY: ".$customlogtext);
		}
	
	}	
	
	//
	//	Generic Delete
	// 
	public static function Destroy($VO, $connection, $rowID)
	{
		// SQL Query
		$StrSQL = "DELETE FROM `" . $VO::$tableName . "` WHERE `".$VO::$keyId."` = ".$rowID;

	
		if( !$res = self::execSQL($connection, $StrSQL) )
		{
			Cogumelo::Error(__METHOD__.": {$connection->error} QUERY: ".$StrSQL, 1001);
			return false;
		}
		else
		{
			Cogumelo::Log("SQL Query: ".__METHOD__.": ".$StrSQL, 5);
			return true;
		}
	}
	
	
	//
	//	Generic Find by ID
	//
	public static function Find($VO, $connection, $rowID)
	{
		// SQL Query
		$StrSQL = "SELECT * FROM `" . $VO::$tableName . "` WHERE `".$VO::$keyId."` = ".$rowID;
	
		if( !$res = self::execSQL($connection, $StrSQL) )
		{
			Cogumelo::Error(__METHOD__.": {$connection->error} QUERY: ".$StrSQL, 1001);
			return false;
		}
		else
		{
			Cogumelo::Log("SQL Query: ".__METHOD__.": ({$res->num_rows} rows found)".$StrSQL, 5);
			if($res->num_rows != 0)
				return self::VOGenerator($VO, $res);
			else
				return false;
		}
	}
	
	
	//
	//	Generic list
	//
	//	Return: array of useradminVOs
	public static function ListAll($VO, $DAO, $connection, $FILTER , $RANGE= false, $ORDER= false)
	{
		
		$whereSTR = $DAO->GenerateFilter($FILTER);
		
		// ORDER IT !
		if($ORDER)
			$orderSTR = self::OrderByString($ORDER);
		else
			$orderSTR =" ";
		
		// If is RANGE
		if(is_array($RANGE))
			$rangeSTR = sprintf(" LIMIT %s, %s ", $RANGE[0], $RANGE[1]);
		//else
			//$rangeSTR = sprintf(" LIMIT %s", $RANGE);
		
		// SQL Query
		$StrSQL = "SELECT * FROM `" . $VO::$tableName . "` ".$whereSTR.$orderSTR.$rangeSTR.";";


		if( !$res = self::execSQL($connection,$StrSQL) )
		{
			Cogumelo::Error(__METHOD__.": {$connection->error} QUERY: ".$StrSQL, 1001);
			return false;
		}
		else
		{
			Cogumelo::Log("SQL Query: ".__METHOD__.": ({$res->num_rows} rows found)".$StrSQL, 5);
			if($res->num_rows != 0){
				return self::VOArrayGenerator($VO, $res);
			}
		else
			return false;
		}
	}
	//
	//	rows number
	public static function ListAllCount($VO, $DAO, $connection, $FILTER)
	{
		$whereSTR = $DAO->GenerateFilter($FILTER);
		
		// SQL Query
		$StrSQL = "SELECT COUNT(*) FROM `" . $VO::$tableName . "`".$whereSTR.";";

		if( !$res = self::execSQL($connection,$StrSQL) )
		{
			Cogumelo::Error(__METHOD__.": {$connection->error} QUERY: ".$StrSQL, 1001);
			return false;
		}
		else
		{
			while( $rowsNO = mysqli_fetch_assoc($res) )
			{
				Cogumelo::Log("SQL Query: ".__METHOD__.": ({$rowsNO['COUNT(*)']} rows found)".$StrSQL, 5);
				return $rowsNO['COUNT(*)'];
			}
		}
	}
}
?>
